import Koa from 'koa'
import { Nuxt, Builder } from 'nuxt'
import Middleware from './middleware'
const path = require('path')
const favicon = require('koa-favicon')
const cors = require('@koa/cors')
const koaBody = require('koa-body')
const router = require('./router')
const validate = require('koa-validate')
// const jwt = require('koa-jwt')
// const pathToRegexp = require('path-to-regexp')
// const ZL = require('../utils/config')

async function start() {
  const app = new Koa()
  const host = process.env.HOST || '0.0.0.0'
  const port = process.env.PORT || '80'

  // 导入和设置Nuxt.js选项配置
  const config = require('../nuxt.config.js')
  config.dev = !(app.env === 'production')

  // 实例化nuxt.js
  const nuxt = new Nuxt(config)

  // 开发模式下编译
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  validate(app)
  // app.keys = ['zlst:session-sign']
  app.use(favicon(path.join(__dirname, '../static/images/favicon.ico'))) // favicon图标
  // .use(Middleware.unauthorizationMiddleware) // 401未授权处理
  .use(Middleware.util) // 添加工具函数
  .use(cors({ credentials: true, maxAge: 1800000 }))
  // .use(jwt({ secret: ZL.jwt.secret }).unless((ctx) => {
  //   // 接口才进行鉴权
  //   if (/^\/api/.test(ctx.path)) {
  //     return pathToRegexp([
  //       '/api/login'
  //     ]).test(ctx.path)
  //   }
  //   return true
  // }))
  .use(koaBody({multipart: true,
    formidable: {
      maxFileSize: 20 * 1024 * 1024 // 设置上传文件大小最大限制，默认20M
    }}))
  .use(router.api.routes())
  .use(router.api.allowedMethods())
  .use(ctx => { // 如果在controller里面设置了ctx.status，则不会进入该中间件
    ctx.status = 200
    ctx.respond = false // Mark request as handled for Koa
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
}

start()
